import math
import os
import shutil

import pandas as pd

from src.bean.config_column_enum import ConfigColumnEnum
from src.util.common_util import printx, while_input, is_int
from src.util.config_manager import ConfigManager
from src.util.file_selector_util import select_multi_file


def split_csv_once(df, output, chunk_size=20000):
    for i in range(math.ceil(len(df) / chunk_size)):
        start = i * chunk_size
        end = start + chunk_size
        chunk = df.iloc[start:end]
        output_file = f"{output}/{i + 1}.csv"
        chunk.to_csv(output_file, index=False)
        printx(f"写入: {output_file}")


def split_files_entrance(config: ConfigManager) -> None:
    file_path_list = select_multi_file(config.get_config(ConfigColumnEnum.use_terminal.value),
                                       title="[文件拆分]请选择要拆分的文件")
    if file_path_list is None:
        return
    df = pd.DataFrame()
    for file_path in file_path_list:
        df = pd.concat([df.reset_index(drop=True), pd.read_csv(file_path).reset_index(drop=True)], ignore_index=True)
    output = input("[文件拆分]请输入保存文件夹位置:")
    chunk_size = int(while_input("[文件拆分]单个文件数据量(建议20000):", is_int))
    if chunk_size <= 0:
        printx("[文件拆分]单文件数据量必须大于0")
        return
    if not os.path.exists(output):
        printx("[文件拆分]文件夹不存在")
        return
    elif not os.path.isdir(output):
        printx("[文件拆分]输入路径不是文件夹")
        return
    else:
        if not os.listdir(output):
            printx("[文件拆分]文件夹存在且为空")
        else:
            printx("[文件拆分]文件夹非空，正在清空...")
            shutil.rmtree(output)
            os.makedirs(output)
        split_csv_once(df, output, chunk_size=chunk_size)
